package com.yyplatform.admin.platform.role.service.impl;

import java.util.List;
import java.util.Optional;

import org.modelmapper.ModelMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yyplatform.admin.platform.role.model.dto.SysDeptDTO;
import com.yyplatform.admin.platform.role.model.dto.SysDeptFormDTO;
import com.yyplatform.admin.platform.role.model.entity.SysDeptEntity;
import com.yyplatform.admin.platform.role.repository.SysDeptRepository;
import com.yyplatform.admin.platform.role.service.SysDeptService;
import com.yyplatform.admin.infra.utils.TreeUtils;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * Created on 2024-09-13
 */
@Slf4j
@Service
@AllArgsConstructor
public class SysDeptServiceImpl implements SysDeptService {

    private ModelMapper modelMapper;
    private SysDeptRepository sysDeptRepository;

    @Override
    public List<SysDeptDTO> listAllForTree() {
        List<SysDeptEntity> dbList = sysDeptRepository.findAll();
        List<SysDeptDTO> dtoList = dbList.stream()
                .map(e -> modelMapper.map(e, SysDeptDTO.class))
                .toList();

        return TreeUtils.build(dtoList, 0L);
    }


    @Override
    public SysDeptDTO get(Long id) {
        if (id == null || id == 0) {
            return null;
        }

        Optional<SysDeptEntity> sysDeptDTOOptional = sysDeptRepository.findById(id);
        return sysDeptDTOOptional.map(e -> modelMapper.map(e, SysDeptDTO.class)).orElse(null);
    }


    @Override
    public void delete(Long id) {
        if (id == null || id == 0) {
            return;
        }
        // todo delete需要做判断，没有被使用才能删除

        sysDeptRepository.deleteById(id);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void update(SysDeptFormDTO sysDeptFormDTO) {
        SysDeptEntity toEntity = modelMapper.map(sysDeptFormDTO, SysDeptEntity.class);

        sysDeptRepository.save(toEntity);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(SysDeptFormDTO sysDeptFormDTO) {
        SysDeptEntity toEntity = modelMapper.map(sysDeptFormDTO, SysDeptEntity.class);
        sysDeptRepository.save(toEntity);
    }


}
